<template>
  <div class="page-container app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" label-width="100px">
        <el-form-item label="用户昵称" prop="nick_name">
          <el-input v-model.trim="searchForm.nick_name" placeholder="请输入用户昵称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleSearch" />
        </el-form-item>
        <el-form-item label="用户来源" prop="user_from">
          <el-select v-model="searchForm.user_from" placeholder="请选择" clearable class="filter-item" style="width: 130px">
            <el-option v-for="(value,key) in optionData.userFromOptions" :label="value.label" :value="value.key" :key="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button class="filter-item ml-10" type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
        <router-link to="/synthetic-case/detail">
          <el-button class="filter-item ml-10" type="primary" icon="el-icon-edit">新增2</el-button>
        </router-link>
        <el-button :loading="downloadLoading" class="filter-item ml-10" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
      </el-form>
    </div>
    <!-- 表格 -->
    <el-table v-loading="tableLoading" :data="tableData" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
      <!-- 序号 -->
      <el-table-column type="index" label="序号" align="center" width="60">
      </el-table-column>
      <el-table-column label="openid" prop="id" sortable="custom" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.openid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" prop="id" align="center" width="100">
        <template slot-scope="scope">
          <img class="user-avatar" src="@/assets/common/user_default.png">
        </template>
      </el-table-column>
      <el-table-column label="时间" width="160" align="center">
        <template slot="header" slot-scope="scope">
          <span>时间</span>
          <span class="caret-wrapper">
            <i :class="sortActiveObj.time == 'asc' ? 'active' : ''" class="sort-caret ascending-normal" @click="sortChangeCustom('asc', 'time')"></i>
            <i :class="sortActiveObj.time == 'desc' ? 'active' : ''" class="sort-caret descending-normal" @click="sortChangeCustom('desc', 'time')"></i>
          </span>
        </template>
        <template slot-scope="scope">
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="150px" align="center">
        <!-- 自定义排序表头，用不到可以忽略 -->
        <template slot="header" slot-scope="scope">
          <span>标题</span>
          <span class="caret-wrapper">
            <i :class="sortActiveObj.title == 'asc' ? 'active' : ''" class="sort-caret ascending-normal" @click="sortChangeCustom('asc', 'title')"></i>
            <i :class="sortActiveObj.title == 'desc' ? 'active' : ''" class="sort-caret descending-normal" @click="sortChangeCustom('desc', 'title')"></i>
          </span>
        </template>
        <template slot-scope="scope">
          <span>{{ scope.row.nick_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="url" width="110px" align="center">
        <template slot-scope="scope">
          <a :href="scope.row.avatar_url" class="link-type" target="_blank">{{ scope.row.avatar_url }}</a>
        </template>
      </el-table-column>
      <el-table-column label="阅读数" align="center" width="95">
        <template slot-scope="scope">
          <span v-if="scope.row.pageviews">{{ scope.row.gain_all }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100" align="center">
        <template slot="header" slot-scope="scope">
          <span>状态</span>
          <span class="caret-wrapper">
            <i :class="sortActiveObj.status == 'asc' ? 'active' : ''" class="sort-caret ascending-normal" @click="sortChangeCustom('asc', 'status')"></i>
            <i :class="sortActiveObj.status == 'desc' ? 'active' : ''" class="sort-caret descending-normal" @click="sortChangeCustom('desc', 'status')"></i>
          </span>
        </template>
        <template slot-scope="scope">
          <el-tag :type="scope.row.user_from | statusFilter">{{ scope.row.user_from }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <router-link :to="'/synthetic-case/edit/'+scope.row.openid">
            <el-button type="primary" size="mini">修改2</el-button>
          </router-link>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 翻页 -->
    <pagination v-show="total>0" :total="total" :page.sync="searchForm.page" :limit.sync="searchForm.limit" @pagination="fetchData" />
    <!-- 弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" center width="540px">
      <el-form ref="dialogForm" :model="dialogForm" label-position="right" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item :rules="formRules.checkRqInput" label="标题" prop="nick_name" required>
          <el-input v-model="dialogForm.nick_name" />
        </el-form-item>
        <el-form-item label="时间" prop="create_time">
          <el-date-picker v-model="dialogForm.create_time" type="datetime" placeholder="请选择" />
        </el-form-item>
        <el-form-item :rules="formRules.checkRqSelect" label="状态" prop="user_from">
          <el-select v-model="dialogForm.user_from" class="filter-item" placeholder="请选择">
            <el-option v-for="(value,key) in optionData.userFromOptions" :label="value.label" :value="value.key" :key="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="点评" prop="remark">
          <el-input v-model="dialogForm.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, createArticle, updateArticle, deleteArticle, exportExcel } from '@/api/table/index';
// 导入表单验证工具
import { checkRqInput, checkRqSelect } from '@/utils/validate';

export default {
  filters: {
    statusFilter (status) {
      const statusMap = {
        Wechat: 'success',
        App: 'gray',
        deleted: 'danger'
      };
      return statusMap[status];
    }
  },
  data () {
    return {
      sortActiveObj: { // 自定义排序
        time: '',
        title: '',
        status: ''
      },
      tableData: [],
      total: 0,
      tableLoading: true,
      // 搜索相关数据
      searchForm: {
        nick_name: '',
        user_from: '',
        limit: 10,
        page: 1,
      },
      // 选择框的数据
      optionData: {
        userFromOptions: [
          { label: '全部', key: '' },
          { label: '微信小程序', key: 'Wechat' },
          { label: '手机应用', key: 'App' }
        ],
      },
      // 新增、修改数据
      dialogForm: {
        openid: '',
        remark: '',
        create_time: new Date(),
        nick_name: '',
        user_from: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      // 校验规则
      formRules: {
        checkRqInput,
        checkRqSelect
      },
      // 导出
      downloadLoading: false
    };
  },
  created () {
    this.fetchData();
  },
  methods: {
    async fetchData () {
      this.tableLoading = true;
      // this.$http(getList(this.searchForm), (res) => {
      //   console.log(res)
      //   this.list = res.d.data
      //   this.total = res.d.total_items
      //   this.tableLoading = false
      // })
      const res = await getList(this.searchForm);
      this.tableLoading = false;
      const { rows, total } = res.data;
      this.tableData = rows;
      this.total = total;
    },
    // 搜索
    handleSearch () {
      this.searchForm.page = 1;
      this.fetchData();
    },
    handleModifyStatus (row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      });
      row.status = status;
    },
    // 排序
    sortChange (data) {
      const { prop, order } = data;
      if (prop === 'id') {
        this.sortByID(order);
      }
    },
    // 自定义排序
    sortChangeCustom (sort, type) {
      this.sortActiveObj[type] = sort;
      // 在这里把this.sortActiveObj里需要的参数统一传给后端就行了
    },
    sortByID (order) {
      if (order === 'ascending') {
        this.searchForm.sort = '+id';
      } else {
        this.searchForm.sort = '-id';
      }
      this.handleSearch();
    },
    // 新增重置弹窗表单
    resetDialogForm () {
      this.dialogForm = {
        openid: '',
        remark: '',
        create_time: new Date(),
        nick_name: '',
        user_from: ''
      };
    },
    // 新增
    handleCreate () {
      this.resetDialogForm();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dialogForm'].clearValidate();
      });
    },
    createData () {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const dialogForm = Object.assign({}, this.dialogForm);
          dialogForm.timestamp = +new Date(dialogForm.timestamp);
          this.$http(createArticle(dialogForm), res => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$message.success('新增成功');
          });
        } else {
          return false;
        }
      });
    },
    // 修改
    handleUpdate (row) {
      this.dialogForm = Object.assign({}, row); // copy obj
      this.dialogForm.create_time = new Date(this.dialogForm.create_time);
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dialogForm'].clearValidate();
      });
    },
    updateData () {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const dialogForm = Object.assign({}, this.dialogForm);
          dialogForm.create_time = +new Date(dialogForm.create_time); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          this.$http(updateArticle(dialogForm), res => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$message.success('更新成功');
          });
        }
      });
    },
    // 删除
    handleDelete (id) {
      this.$confirm('删除', `确认删除吗`, () => {
        this.$http(deleteArticle(id), res => {
          this.$message.success(res.m);
          this.fetchData();
        });
      });
    },
    // 导出
    handleDownload () {
      exportExcel({
        nick_name: this.searchForm.nick_name,
        user_from: this.searchForm.user_from
      });
    }
  }
};
</script>
<style lang='scss' scoped>
</style>
